<?php

declare (strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Model;

use App\Server\ArrjoinCasts;
use App\Server\StrtotimeCasts;
use Hyperf\DbConnection\Model\Model as BaseModel;
abstract class Model extends BaseModel
{
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    const DELETED_AT = 'delete_time';
    protected array $guarded = [];
    /**
     * 根据id初始化
     *
     * @param $id
     * @return $this
     */
    public static function initById($id, $columns = ['*'], $withTrashed = false)
    {
        if ($withTrashed) {
            return static::withTrashed()->findOrFail($id, $columns);
        } else {
            return static::findOrFail($id, $columns);
        }
    }
    /**
     * 根据id获取对象
     *
     * @param $id
     * @return $this
     */
    public static function getById($id, $columns = ['*'], $withTrashed = false)
    {
        if ($withTrashed) {
            return static::withTrashed()->find($id, $columns);
        } else {
            return static::find($id, $columns);
        }
    }
    /**
     * 设置属性默认值
     * @param $key
     * @param $value
     * @return Model|\Hyperf\Database\Model\Model|void
     */
    public function setAttribute($key, $value)
    {
        parent::setAttribute($key, $this->setAttributeDefaultValue($key, $value));
    }
    /**
     * 设置属性默认值
     * @param $key
     * @param $value
     * @return mixed
     */
    public function setAttributeDefaultValue($key, $value) : mixed
    {
        $casts = $this->casts[$key] ?? '';
        if ($casts && (is_null($value) || is_string($value) && strlen($value) === 0)) {
            $value = match ($casts) {
                //                StrtotimeCasts::class, 'int', 'integer', 'real', 'float', 'double', 'boolean', 'bool', 'decimal' => 0,
                //                ArrjoinCasts::class, 'object', 'array', 'json' => [],
                default => null,
            };
        }
        return $value;
    }
}